/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taskmanager2ndedition.client;

import java.beans.XMLEncoder;
import java.io.ByteArrayOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import taskmanager2ndedition.Cmd;
import java.lang.reflect.Method;
import taskmanager2ndedition.Connection;
import taskmanager2ndedition.ClientUser;
import taskmanager2ndedition.exceptions.*;

/**
 *
 * @author Александр
 * 
 *  Command interpreter
 * 
 */
public class CmdInterpretator {
    
    private Connection connection;
    private static ClientController controller;
    
    public static void setController(ClientController controller){
        CmdInterpretator.controller = controller;                
    }
    
    public void setConnection(Connection val){
        connection  = val;
    }
    
    public Connection getConnection(){
        return connection;
    }
    
    public synchronized String generateRequest(Cmd cmd){
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        XMLEncoder encoder = new XMLEncoder(outputStream);
        encoder.writeObject(cmd);
        encoder.flush();
        encoder.close();
        return outputStream.toString();
    }
   
    public synchronized Object performResponce(String cmdString) throws Exception{
        Object result = null;
        if (cmdString == null){
            return null;
        }

        Cmd response = Cmd.fromString(cmdString);
        if (response.getParams()!= null && !response.getParams().isEmpty()){
            result = response.getParams().get(0);
            if (result instanceof Exception)
                throw (Exception)result;
        }
        
        return result;
    }
    
    private synchronized Method findMethod(Cmd cmd){
        try {
            Class [] params = new Class[cmd.getParams().size()];
            for (int i = 0; i < cmd.getParams().size(); i++){
                params[i] = cmd.getParams().get(i).getClass();
            }
            return ClientController.class.getMethod(cmd.getMethod(), params);
        } catch (Exception ex){
            Logger.getLogger(CmdInterpretator.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }
}
